package utils;

import java.awt.*;

/**
 * This class is responsible for managing the splash screen while the
 * rest of the program is loading.
 */
public class Splash extends Thread{

    /**
     * Draws dots on the splash screen
     * @param g the graphics context for the splash screen
     * @param frame (frame/5)%4 will determine the number of dots drawn.
     */
    private void renderSplashFrame(Graphics2D g, int frame) {
        final String[] comps = {"", ".", "..", "..."};
        g.setComposite(AlphaComposite.Clear);
        g.fillRect(380,40,410,60);
        g.setPaintMode();
        g.setColor(Color.BLACK);
        g.setFont(new Font("Serif", 20, 40));
        g.drawString(comps[(frame/5)%4], 390, 50);
    }

    /**
     * Interrupts this thread if it has been running
     * for more than 3 seconds. Else it waits until this
     * criterion is satisfied before interrupting.
     */
    @Override
    public void interrupt(){
        while(looping){
            ct = System.currentTimeMillis();
            if((ct - st) > 3000){
                running = false;
                break;
            }
        }
        super.interrupt();
    }

    /**
     * System time in milliseconds
     */
    private long st, ct;
    /**
     * Is the thread running - maybe use isAlive instead?
     */
    private boolean running = true;
    /**
     * has the run() method reached its render loop?
     */
    private boolean looping = false;

    /**
     * @return is the splash screen redrawing?
     */
    public boolean isLooping(){
        return looping;
    }

    @Override
    public void run(){
        try{
        st = System.currentTimeMillis();
        final SplashScreen splash = SplashScreen.getSplashScreen();
        if (splash == null) {
            System.err.println("SplashScreen.getSplashScreen() returned null");
            interrupt();
            return;
        }
        System.out.println("Splash: creating graphics context");
        Graphics2D g = splash.createGraphics(); //DEADLOCK warning
        System.out.println("Splash: graphics context created");
        if (g == null) {
            System.err.println("Splash: g is null");
            interrupt();
            return;
        }
        looping = true;
        int i = 1;
        while (running) {
            renderSplashFrame(g, i);
            splash.update();
            try {
                Splash.sleep(90);
            }
            catch(InterruptedException e) {
                break;
            }
            i++;
        }
        looping = false;
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
